package com.example.mardan.repository;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.example.mardan.entity.YuanquChapter;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class YuanquRepository {
    private static final String TAG = "YuanquRepository";
    private static final String API_URL = "https://api.jisuapi.com/yuanqu/chapter?appkey=31909fc69575bf5b";
    private MutableLiveData<List<YuanquChapter.ResultDTO>> yuanquListLiveData;
    private OkHttpClient client;

    public YuanquRepository() {
        yuanquListLiveData = new MutableLiveData<>();
        client = new OkHttpClient();
    }

    public MutableLiveData<List<YuanquChapter.ResultDTO>> getYuanquList() {
        if (yuanquListLiveData.getValue() == null) {
            fetchYuanquList();
        }
        return yuanquListLiveData;
    }

    private void fetchYuanquList() {
        Request request = new Request.Builder()
                .url(API_URL)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "Error fetching data: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String json = response.body().string();
                    Gson gson = new Gson();
                    YuanquChapter yuanquResponse = gson.fromJson(json, YuanquChapter.class);
                    if (yuanquResponse!= null && yuanquResponse.getResult()!= null) {
                        List<YuanquChapter.ResultDTO> yuanquList = yuanquResponse.getResult();
                        yuanquListLiveData.postValue(yuanquList);
                    }
                } else {
                    Log.e(TAG, "Error fetching data: " + response.code());
                }
            }
        });
    }
}